package com.gqj.web.controller.system;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import com.gqj.common.config.RuoYiConfig;
import com.gqj.common.utils.file.FileUploadUtils;
import com.gqj.common.utils.file.FileUtils;
import com.gqj.framework.config.ServerConfig;
import com.gqj.system.hk.FaceManage;
import com.gqj.system.hk.UserManage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.domain.entity.SysDept;
import com.gqj.common.core.domain.entity.SysRole;
import com.gqj.common.core.domain.entity.SysUser;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.SecurityUtils;
import com.gqj.common.utils.StringUtils;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.system.service.ISysDeptService;
import com.gqj.system.service.ISysPostService;
import com.gqj.system.service.ISysRoleService;
import com.gqj.system.service.ISysUserService;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Api(value = "/system/user", description = "用户信息")
@RestController
@RequestMapping("/system/user")
public class
SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private final ServletContext servletContext;

    public SysUserController(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @ApiOperation("用户管理")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @ApiOperation("用户明细导入")
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("根据用户编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setRealPassword(user.getPassword());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int row = userService.insertUser(user);
        if (row == 1) {
            // 下发到门禁
            try {
                UserManage.addUserInfo(user.getUserName(), user.getNickName());
                if (!StringUtils.isEmpty(user.getFace())) {
                    String facePath = user.getFace().replace("/profile", RuoYiConfig.getProfile());
                    FaceManage.addFaceByBinary(user.getUserName(), facePath);
                }
            } catch (Exception exception) {

            }
        }
        return toAjax(row);
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) throws UnknownHostException, JSONException, InterruptedException {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        // 原数据
        SysUser oldSysUser = userService.selectUserById(user.getUserId());
        int row = userService.updateUser(user);
        if (row == 1) {
            // 如果更新人脸，删除原图片
            if (oldSysUser.getFace()==null||!oldSysUser.getFace().equals(user.getFace())) {
                // 删除人脸图片
                if (oldSysUser.getFace() != null) {
                    String facePath = oldSysUser.getFace().replace("/profile", RuoYiConfig.getProfile());
                    FileUtils.deleteFile(facePath);
                    FaceManage.deleteFaceInfo(user.getUserName());
                }
                String facePath = user.getFace().replace("/profile", RuoYiConfig.getProfile());
                FaceManage.addFaceByBinary(user.getUserName(), facePath);
            }
        }
        return toAjax(row);
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete")
    public AjaxResult remove(@RequestParam("ids") String userIds) throws JSONException {
        String[] userIdStrArray = userIds.split(",");

        Long[] userIdArray = new Long[userIdStrArray.length];

        for (int i = 0; i < userIdStrArray.length; i++) {
            userIdArray[i] = Long.parseLong(userIdStrArray[i]);
        }

        if (ArrayUtils.contains(userIdArray, getUserId())) {
            return error("当前用户不能删除");
        }
        int row = userService.deleteUserByIds(userIdArray);

        for (long userId : userIdArray) {
            // 删除海康人员信息
            SysUser user = userService.selectUserById(userId);
            UserManage.deleteUserInfo(user.getUserName());
            // 删除人脸图片
            if(user.getFace()!=null) {
                String facePath = user.getFace().replace("/profile", RuoYiConfig.getProfile());
                FileUtils.deleteFile(facePath);
            }
        }

        return toAjax(row);
    }

    /**
     * 采集人脸
     */
    @ApiOperation("采集人脸")
    @PreAuthorize("@ss.hasPermi('system:user:caputreFace')")
    @Log(title = "用户管理", businessType = BusinessType.CAPTURE_FACE)
    @PutMapping("/captureFace")
    public AjaxResult captureFace() throws IOException {
        boolean isSuc = false;
        String fileName = FaceManage.captureFaceInfo();
        if(StringUtils.isNotEmpty(fileName)) {
            String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getFacePath(), fileName.replace(RuoYiConfig.getFacePath() + File.separator, ""));
            System.out.println(pathFileName);
            return StringUtils.isEmpty(pathFileName) ? error("出错了") : AjaxResult.success("成功", pathFileName);
        }else{
            return error("出错了");
        }
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @ApiOperation("根据用户编号获取授权角色")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @ApiOperation("用户授权角色")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @ApiOperation("获取部门树列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

//    /**
//     * 论坛多图片上传 直接用的若依图片上传的封装方法
//     */
//    @Log(title = "论坛多图片上传", businessType = BusinessType.UPDATE)
//    @PostMapping("/multiPicturesUpload")
//    public AjaxResult multiPicturesUpload(MultipartFile file) throws IOException {
//        //RuoYiConfig.getForumPath() 获取自定义该模块的图片保存路径
//        if (!file.isEmpty()){
//            //获取上传成功的图片保存路径，并返回给前台
//            String picture = FileUploadUtils.imgUpload(RuoYiConfig.getForumPath(), file);
//            if (!StringUtils.isEmpty(picture)){
//                AjaxResult ajax = AjaxResult.success();
//                ajax.put("imgUrl", picture);
//                return ajax;
//            }
//        }
//        return AjaxResult.error("上传图片异常，请联系管理员");
//    }


    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/uploadFace")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            System.out.println(file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

}
